import {
  baseUrl
} from './env'
import {
  Toast
} from 'vant';
import {
  wxLoginOAuth
} from "src/service/weiXinCommon";
import {
  loginOut,
  getToken
} from "src/service/common";

export default async (url = '', data = {}, type = 'GET', method = 'fetch') => {
  let project_token = 18031201;
  let token = getToken();
  type = type.toUpperCase();
  url = baseUrl + url;

  if (type == 'GET') {
    let dataStr = ''; //数据拼接字符串
    Object.keys(data).forEach(key => {
      dataStr += key + '=' + data[key] + '&';
    })

    if (dataStr !== '') {
      dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
      url = url + '?' + dataStr;
    }
  }

  if (window.fetch && method == 'fetch') {
    let requestConfig = {
      // credentials: 'include', 当请求的凭据模式为“include”时，响应中的标头不能是通配符“*”
      method: type,
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'project_token': project_token,
        'user_token': token,
      },
      //mode: 'cors', 
      cache: "force-cache"
    }

    if (type == 'POST') {
      Object.defineProperty(requestConfig, 'body', {
        value: JSON.stringify(data)
      })
    }
    try {
      const response = await fetch(url, requestConfig);
      const responseJson = await response.json();
      if (parseInt(responseJson.code) == 1000) { //未登录。
        const t = Toast({
          message: responseJson.info,
          duration: 2000
        });
        console.log(t);
        t.close = () => {
          //退出登录
          loginOut();
          //重定向到登录页面
          wxLoginOAuth();
        }

        return;
      }
      if (!responseJson || !responseJson.success) {
        Toast({
          message: responseJson.info,
          duration: 2000
        });
      }
      
      return responseJson || {};
    } catch (error) {
      throw new Error(error)
    }
  } else {
    return new Promise((resolve, reject) => {
      let requestObj;
      if (window.XMLHttpRequest) {
        requestObj = new XMLHttpRequest();
      } else {
        requestObj = new ActiveXObject;
      }

      let sendData = '';
      if (type == 'POST') {
        sendData = JSON.stringify(data);
      }

      requestObj.open(type, url, true);
      requestObj.setRequestHeader("Content-type", "application/json");
      requestObj.setRequestHeader("user_token", token);
      requestObj.setRequestHeader("project_token", project_token);
      requestObj.send(sendData);

      requestObj.onreadystatechange = () => {
        if (requestObj.readyState == 4) {
          if (requestObj.status == 200) {
            let obj = requestObj.response
            if (typeof obj !== 'object') {
              obj = JSON.parse(obj);
            }
            if (parseInt(obj.code) == 1000) { //未登录。
              const t = Toast({
                message: obj.info,
                duration: 2000
              });
              console.log(t);
              t.close = () => {
                //退出登录
                loginOut();
                //重定向到登录页面
                wxLoginOAuth();
              }
              return;
            }
            if (!obj || !obj.success) {
              Toast({
                message: obj.info,
                duration: 2000
              });
            }
            resolve(obj)
          } else {
            reject(requestObj)
          }
        }
      }
    })
  }
}
